<script>
import DeviceForm from '../../components/device/deviceForm.vue'

import DeviceApi from '../../api/device'

export default {
  components: {
    DeviceForm
  },
  data() {
    return {
      device: {},
    }
  },
  methods: {
    async getDevice(deviceId) {
      try {
        const api = new DeviceApi()
        let res = await api.find(deviceId)
        this.device = res.data
        console.log(this.device)
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    async deviceSave() {
      if (this.device.title && this.device.xiamenId) {
        try {
          const api = new DeviceApi()
          
          let res = await api.edit(this.device)
          console.log(res)
          if (res.code === 200) {
            this.$myMessageBox(res.msg)
            this.$router.push({ name: 'device-list' })
          }
        } catch (err) {
          console.error(err)
          this.$myMessageBox('应用服务器访问错误！')
        }
      } else {
        this.$myMessageBox('设备名称与xiamenId号信息不完整！')
      }
    },
   
  },
  mounted() {
    let deviceId = this.$route.params.id
    try {
      let device = JSON.parse(sessionStorage.getItem(`device-${deviceId}`) || 'null')
      if (device && device.id === deviceId) {
        this.device = device
      } else {
        this.getDevice(deviceId)
      }
    } catch (err) {
      console.error('Error parsing device data:', err)
      this.getDevice(deviceId)
    }
  },
}
</script>

<template>
  <div class="device-edit w80">
    <div class="header">
      <h2>编辑设备</h2>
      <p>
        <a class="button" href="javascript:void(0)" @click="$goBack">返回</a>
      </p>
    </div>
    <div class="block">
      <device-form v-model="device" @device-save="deviceSave"></device-form>
    </div>
  </div>
</template>

<style scoped></style>
